package kit;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import domain.Movie;
import function.GobleVar;
import function.GobleTool;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class FileIO
{
	ObjectMapper objectMapper = new ObjectMapper();

	public void readEndingResult(String file_path) throws IOException
	{
		ArrayList<String> contentList = readFile(file_path);
		for (int i=0;i<contentList.size();i++)
		{
			String conten[] = contentList.get(i).split("::");
			//TODO:可以反序列化整个集合，加速计算，收益较小暂不优化
			GobleVar.endingResult.put(Integer.parseInt(conten[0]),objectMapper.readValue(conten[1], new TypeReference<List<Map.Entry<Integer,Double>>>(){}));
		}
	}

	public void readMovieList(String file_path) throws IOException
	{
		ArrayList<String> contentList = readFile(file_path);
		for (int i=0;i<contentList.size();i++)
		{
			String conten[] = contentList.get(i).split("::");
			GobleVar.movieList.put(Integer.parseInt(conten[0]),objectMapper.readValue(conten[1], new TypeReference<Movie>(){}));
		}
	}

	public ArrayList<String> readFile(String file_path) throws IOException
	{
		ArrayList<String> result = new ArrayList<>();
		File file;
		FileReader fr;
		BufferedReader br;
		GobleTool.printInfo("正在读入文件："+file_path+",请稍后...");
		file = new File(file_path);
		if (!file.exists())
			return null;
		fr = new FileReader(file);
		br = new BufferedReader(fr);
		String lineText;
		while(br.ready())
		{
			lineText = br.readLine();
			result.add(lineText);
		}
		br.close();
		return result;
	}
}
